package de.siegmar.fastcsv.util;

import java.io.IOException;
import java.io.InputStream;

import de.siegmar.fastcsv.reader.BomUtil;

/**
 * 兼容性工具类
 */
public class Compatible {
    public static int readNBytes(InputStream inputStream, byte[] buffer) throws IOException {
        int bytesRead = 0;
        int currentRead;
        while (bytesRead < BomUtil.POTENTIAL_BOM_SIZE) {
            currentRead = inputStream.read(buffer, bytesRead, BomUtil.POTENTIAL_BOM_SIZE - bytesRead);
            if (currentRead == -1) {
                break; // 到达流末尾，提前终止
            }
            bytesRead += currentRead;
        }
        return bytesRead;
    }

    public static byte[] readNBytes(InputStream inputStream, int size) throws IOException {
        byte[] buf = new byte[size];
        int bytesRead = 0;
        int currentRead;
        while (bytesRead < size) {
            currentRead = inputStream.read(buf, bytesRead, size - bytesRead);
                if (currentRead == -1) {
                    break;
                }
                bytesRead += currentRead;
            }
            // 截取实际读取到的字节（避免数组后面的空字节影响检测）
            byte[] actualBuf = new byte[bytesRead];
            System.arraycopy(buf, 0, actualBuf, 0, bytesRead);
            return actualBuf;
    }
}
